package com.aliya.glide.okhttp

import com.bumptech.glide.load.Options
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.ModelLoader
import com.bumptech.glide.load.model.ModelLoader.LoadData
import com.bumptech.glide.load.model.ModelLoaderFactory
import com.bumptech.glide.load.model.MultiModelLoaderFactory
import okhttp3.Call
import okhttp3.OkHttpClient
import java.io.InputStream


/**
 * OkHttpUrlLoader
 *
 * @author a_liYa
 * @date 2021/11/1 22:21.
 *
 */
class OkHttpUrlLoader(private val client: Call.Factory): ModelLoader<GlideUrl, InputStream> {

    override fun handles(url: GlideUrl): Boolean {
        return true
    }

    override fun buildLoadData(
        model: GlideUrl, width: Int, height: Int, options: Options
    ): LoadData<InputStream?>? {
        return LoadData(model, OkHttpStreamFetcher(client, model))
    }

    /**
     * Constructor for a new Factory that runs requests using given client.
     *
     * @param client this is typically an instance of `OkHttpClient`.
     */
    /** The default factory for [OkHttpUrlLoader]s.  */ // Public API.
    class Factory @JvmOverloads constructor(private val client: Call.Factory) :
        ModelLoaderFactory<GlideUrl, InputStream> {

        override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<GlideUrl, InputStream> {
            return OkHttpUrlLoader(client)
        }

        override fun teardown() {
            // Do nothing, this instance doesn't own the client.
        }

    }
}